package com.lqian.simplestructure.stack;

import java.util.Arrays;

public class MyStack {
    int[] elements;

    public MyStack(){
        this.elements = new int[0];
    }

    //压入元素
    public void push(int element){
        int[] newArr = new int[elements.length + 1];
        for (int i = 0; i < elements.length; i++){
            newArr[i] = elements[i];
        }
        newArr[newArr.length - 1] = element;
        elements = newArr;
    }

    //取出栈顶元素
    public int pop(){
        //判断是否为空栈
        if (elements.length == 0){
            throw new RuntimeException("Stack is empty");
        }

        int[] newArr = new int[elements.length - 1];
        int element = elements[elements.length - 1 ];
        for (int i = 0; i <= newArr.length - 1;i++){ // or  -->  for (int i = 0; i < elements.length - 1;i++)
            newArr[i] = elements[i];
        }

        elements = newArr;
        return element;
    }
    //查看栈顶元素
    public int peek(){
        //判断是否为空栈
        if (elements.length == 0){
            throw new RuntimeException("Stack is empty");
        }

        return elements[elements.length - 1];
    }

    //查看栈内的元素
    public void show(){
        System.out.println(Arrays.toString(elements));
    }

    //判断栈是否为空
    public boolean isEmpty(){
        return elements.length == 0;
    }

    //test
    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.push(4);
        myStack.show();
        System.out.println(myStack.isEmpty());
        System.out.println(myStack.peek());
        myStack.pop();
        myStack.pop();
        myStack.pop();
        myStack.pop();
        System.out.println(myStack.isEmpty());



    }

}
